package com.mjlf.mqzook.client;

import com.alibaba.fastjson.JSONObject;
import com.mjlf.mqzook.config.ZkClientConfig;
import com.mjlf.mqzook.entity.RegistryServer;
import com.mjlf.mqzook.inter.RegistryFacotry;
import com.mjlf.mqzook.schedule.ServerClear;
import com.mjlf.restclient.entity.RestParams;
import com.mjlf.restclient.template.RestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.Set;

/**
 * @ClassName ZkClientSchedule
 * @Author mjlft
 * @Date 2020/2/18 14:45
 * @Version 1.0
 * @Description 客户端注册
 */
@Component
public class ZkClientSchedule {
    Logger logger = LoggerFactory.getLogger(ZkClientSchedule.class);

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private ZkClientConfig clientConfig;

    @Scheduled(cron = "${client.corn}")
    public void registry(){
        RestParams restParams = new RestParams();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", clientConfig.getApplicationName());
        jsonObject.put("host", clientConfig.getHost());
        jsonObject.put("port", clientConfig.getPort());
        restParams.setParams(jsonObject.toJSONString());
        restParams.setUrl(clientConfig.getUrl());
        try {
            String result = restTemplate.post(restParams);
            JSONObject jsonObject1 = JSONObject.parseObject(result);
            if(jsonObject1.getInteger("code") != 200){
                throw new Exception("resitry error");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("服务注册{}:{}", clientConfig.getHost(), clientConfig.getPort());
    }
}
